import { onMounted, Ref } from "vue";
import { get } from "lodash-es";

export interface AiFetchResult<T> {
  code: number;
  msg: string;
  result: T;
  totalSize?: number;
}

interface TableConfigOption {
  current?: number;
  size?: number;
  lazyLoad?: boolean;
  resultKey?: string;
}

export const useAsiaTable = <T, P>(
  api: (...args: any[]) => Promise<AiFetchResult<P[]>>,
  params: Ref<T>,
  option: TableConfigOption,
) => {
  // 默认配置
  const {
    current: _current = 1,
    size: _size = 10,
    lazyLoad = false,
    resultKey = "result",
  } = option;
  // 表格数据声明
  const loading = ref(false);
  const dataSource = ref<P[]>([]);
  const current: Ref<number> = ref(_current);
  const size: Ref<number> = ref(_size);
  const total: Ref<number> = ref(0);

  /**
   * 分页查询
   * @param _current 当前页码
   * @param _size 每页条数
   * @returns Promise<void>
   */
  const page = async (_current: number, _size: number) => {
    loading.value = true;
    current.value = _current;
    size.value = _size;
    try {
      const res = await api({
        ...unref(params.value),
        current: _current,
        size: _size,
      });
      total.value = res.totalSize as number;
      dataSource.value = get(res, resultKey as string);
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 查询当前表格数据
   * @returns Promise<void>
   */
  const search = async () => {
    page(1, size.value);
  };

  /**
   * 刷新当前表格数据
   * @returns Promise<void>
   */
  const refresh = async () => {
    page(current.value, size.value);
  };

  /**
   * 切换分页，用于表格内嵌的分页组件
   * @param pagination 分页信息，有current和pageSize两个属性
   * @returns Promise<void>
   */
  const changeForTable = (pagination: {
    current: number;
    pageSize: number;
  }) => {
    page(pagination.current, pagination.pageSize);
  };

  /**
   * 切换分页，用于antd独立的分页组件
   * @param _current 当前页
   * @param _pageSize 每页大小
   * @returns Promise<void>
   */
  const changeForPagination = (_current: number, _pageSize: number) => {
    page(_current, _pageSize);
  };

  onMounted(() => {
    if (!lazyLoad) {
      page(current.value, size.value);
    }
  });

  return {
    loading,
    dataSource,
    current,
    size,
    total,
    page,
    search,
    refresh,
    changeForTable,
    changeForPagination,
  };
};
